import time
import json
# import pandas as pd
import requests
import websocket
from requests.adapters import HTTPAdapter
import time
import ssl
import pymongo
import base64
import re
import gzip
import hashlib

try:
    import thread
except ImportError:
    import _thread as thread


def __init__():
    pass



unknow_key = "NTI3MTQ2NTA3MiRiY2E1ZWMyYS02ODUzLTQ5ZDAtYmI1My1jNzUxN2NmODZlODR" # base64解码后 => 5271465072$bca5ec2a-6853-49d0-bb53-c7517cf86e84

# feedId = "997cf8e1-8a6b-4307-9102-34122ba0649c" # 主播 feedId
feedId = "45c8cb02-acb3-44af-aa34-90100ca63118" # 主播 feedId
bytesStr = feedId.encode(encoding='utf-8')
bytesStr.decode()
b64str = base64.b64encode(bytesStr)
b64str = b64str.decode("utf8","ignore")

SEND_DATA = "igkgCAH4AAok{}EAEiCWg1XzAuNC4xOCqPATUuMCAoTWFjaW50b3NoOyBJbnRlbCBNYWMgT1MgWCAxMF8xNF81KSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNzcuMC4zODY1LjkwIFNhZmFyaS81MzcuMzYgTGliTWVzc2FnZUtpdFNkay8xNTcw{}CCTcyOTEzMjc3NEoAEAAKDnRiOTEwMDk5NV8yMDExAAA=".format(b64str, unknow_key)


# GZIP解密
def decode_gzip (base64_str):
    res = base64.b64decode(base64_str)
    res = gzip.decompress(res).decode('utf8',"ignore")
    return res

# Base64解密
def decode_base64 (base64_str):
    res = base64.b64decode(base64_str)
    return res

def findNum (key, origin_str):
    res = re.findall('\"' + key + '\":(.*?)(,\"|})', origin_str)
    if len(res) > 0:
        return res
    else:
        return False

def findStr (key, origin_str):
    res = re.findall('\"' + key + '\":\"(.*?)(\",\"|\"})', origin_str)
    if len(res) > 0:
        return res
    else:
        return False


# 这里就是websocket爬虫的核心，发送请求，接收数据并做最后处理，
def on_message(ws, message):
    res_dict = json.loads(message)

    # 判断 data 是否为空
    if res_dict['data'] == '':
        print('data为空')
        return
    print("{} - {}".format(res_dict['compressType'], res_dict['data']))

    if res_dict['compressType'] == 'COMMON':
        res_str = decode_base64(res_dict['data'])
        res_str = res_str.decode("utf8","ignore").strip().replace('\n','').replace('\n', '')
    else:
        res_str = decode_gzip(res_dict['data'])
        res_str = res_str.strip().replace('\n','').replace('\n', '')

    # cachedSize = findNum('cachedSize', res_str)
    # if cachedSize is not False:
    #     print('cachedSize：{}'.format(cachedSize[0][0]))

    onlineCount = findNum('onlineCount', res_str)
    if onlineCount is not False:
        print('onlineCount：{}'.format(onlineCount[0][0]))

    pageViewCount = findNum('pageViewCount', res_str)
    if pageViewCount is not False:
        print('pageViewCount：{}'.format(pageViewCount[0][0]))

    # serializedSize = findNum('serializedSize', res_str)
    # if serializedSize is not False:
    #     print('serializedSize：{}'.format(serializedSize[0][0]))

    totalCount = findNum('totalCount', res_str)
    if totalCount is not False:
        print('totalCount：{}'.format(totalCount[0][0]))


    userid = findNum('userid', res_str)
    if userid is not False:
        # fanLevel = findNum('fanLevel', res_str)
        nick = findNum('nick', res_str)
        print(userid[0:-1])
        print(nick[0:-1])

    print('----------------------------------------------------')


def on_error(ws, error):
    print(error)


# 关闭websocket长连接
def on_close(ws):
    print("关闭连接")

# 程序运行第一步
def on_open(ws):
    def run(*args):
        send_content = {
            "data": SEND_DATA,
            "dataId": "3504211_4409",
            "protocol": "ACCS_H5",
            "serviceId": "powermsg",
            "type": "REQ",
        }
        send_content = json.dumps(send_content)
        ws.send(send_content)
        print("thread terminating...")
    thread.start_new_thread(run, ())


def get_token(my_cookie):
    for i in range(3):
        try:
            url = 'https://acs.m.taobao.com/h5/mtop.mediaplatform.live.encryption/1.0/'

            headers = {
                "Referer": "http://huodong.m.taobao.com/act/talent/live.html",
                "Sec-Fetch-Mode": "no-cors",
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
            }

            data = {"appKey": "H5_4282", "windowId": "2046630410_667"}
            data = str(data)
            APPKEY = '12574478'
            params = {
                'AntiCreep': 'true',
                'jsv': '2.5.0',
                'appKey': APPKEY,
                't': int(time.time() * 1000),
                'sign': 'FAKE_SIGN_WITH_ANYTHING',
                'api': 'mtop.mediaplatform.live.encryption',
                'v': '1.0',
                'type': 'json',
                'dataType': 'json',
                "sdkversion": "h5_1.3.7",
                'callback': 'mtopjsonp3',
                'data': data
            }
            headers['Cookie'] = my_cookie
            token_with_time = re.findall('_m_h5_tk=(.*?);', my_cookie)[0]
            token = token_with_time.split('_')[0]
            t2 = str(int(time.time() * 1000))
            c = '&'.join([token, t2, APPKEY, data])
            m = hashlib.md5()
            m.update(c.encode('utf-8'))
            params.update({'t': t2, 'sign': m.hexdigest()})

            r2 = requests.get(url, params=params, headers=headers)
            return json.loads(r2.text)
        except:
            continue


if __name__ == "__main__":
    print(SEND_DATA)
    # 获取 cookie
    myclient = pymongo.MongoClient("mongodb://47.98.146.210:27017")
    mydb_cookies = myclient["QK_GOODS"]
    mycol_cookies = mydb_cookies['qk_cookies']
    cookiee = mycol_cookies.find({}).sort([('_id', -1)]).limit(1)
    for cook in cookiee:
        my_cookie = cook['qk_taobao']

    header = {
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,',
        'Cache-Control': 'no-cache',
        'Connection': 'Upgrade',
        'Cookie': my_cookie,
        'Host': 'acs.m.taobao.com:80',
        'Origin': 'https://taobaolive.taobao.com',
        'Pragma': 'no-cache',
        'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
        # 这个参数要进行实时修改
        'Sec-WebSocket-Key': 'WV9B4PXjzHvsFOaK4Vuzzg==',
        'Sec-WebSocket-Version': '13',
        'Upgrade': 'websocket',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
    }

    # 获取 token
    res_token = get_token(my_cookie)
    print(res_token)
    token = res_token['data']['result']
    print('直播token: {}'.format(token))

    websocket.enableTrace(True)
    # websocket_obj = websocket_class()
    # url = "wss://acs.m.taobao.com:80/accs/auth?token=AAADXZxTEiaciamn6JL9GUnCCfLl7nnCdVzxfj/+1s+uht78ocghoCzFK8lSo/2jP7E4Ljr82j01vHOEdq0+FKSHGkrlDBE="
    # url = "wss://acs.m.taobao.com:80/accs/auth?token=AAAFXZxUdJwIZh5IVzh+XmykJpc0cEZZo2XWqHNGCsKOdSqeiRFlzZtqheGLbJtaFkTMpkKU92kxUDMqyvjq5oS7Uhl5gZ8="
    url = "wss://acs.m.taobao.com:80/accs/auth?token={}".format(token)
    print(url)
    ws = websocket.WebSocketApp(url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close,
                                header=header)

    ws.on_open = on_open
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})